package com.wsc.springbootrabbitmq.producer;

import com.wsc.springbootrabbitmq.pojo.User;
import com.wsc.springbootrabbitmq.producer.callback.MyCallbacks;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHeaders;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.UUID;

/**
 *  消息生产端
 */
@Component
public class RabbitSender {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private MyCallbacks myCallbacks;

    /**
     * 发送消息
     * @param message message 类型的消息
     * @param properties 消息配置
     * @throws Exception
     */
    public void send(Object message, Map<String,Object> properties) throws Exception{
        MessageHeaders headers = new MessageHeaders(properties);
        Message msg = MessageBuilder.createMessage(message, headers);
        //设置消息确认模式
        rabbitTemplate.setConfirmCallback(myCallbacks.confirmCallback());
        //设置消息返回模式
        rabbitTemplate.setReturnCallback(myCallbacks.returnCallback());
        //根据业务规则设定一个唯一消息 id + 时间戳 ，要通过这个 Id 找到唯一的一条消息
        CorrelationData correlationData = new CorrelationData();
        correlationData.setId("1"+UUID.randomUUID());
        rabbitTemplate.convertAndSend("spb_exchange", "springboot.msg",msg,correlationData);
    }

    /**
     * 发送 User 类型消息
     * @param user user
     * @throws Exception
     */
    public void userSend(User user) throws Exception{
        //设置消息确认模式
        rabbitTemplate.setConfirmCallback(myCallbacks.confirmCallback());
        //设置消息返回模式
        rabbitTemplate.setReturnCallback(myCallbacks.returnCallback());
        //根据业务规则设定一个唯一消息 id + 时间戳 ，要通过这个 Id 找到唯一的一条消息
        CorrelationData correlationData = new CorrelationData();
        correlationData.setId("1"+ UUID.randomUUID());
        rabbitTemplate.convertAndSend("spb_exchange", "springboot.user",user,correlationData);
    }

}
